import PageTemplate from '@/components/common/PageTemplate'
import procApprove from '@/components/common/procApprove'
import fixedbutton from '@/components/common/fixedbutton'
import download from '@/components/common/download'
import store from '@/store'

import {getWinDetailsById,findFileList,getNextNode,getBpmPscActInfo,
    getApprovePerson,editDraft,delFile,commitWinAndDraft,
    getNextApprovePerson,getStartAct,getWFConfigActivity
} from '@/api/api'

export default {
    components:{
      PageTemplate,
        procApprove,
        fixedbutton,
        download
    },
    data() {
        return {
            brand:[
                {name:'lang.workbench'},
                {name:'dft.draftEdit'},
            ],
            hasIcon:false,
            win:{
                cudWinLevel:'', //中奖等级
                cudPrizeAmount:'',//奖金额度
                cudWinName:'',//获奖者姓名
                cudPhone:'',//联系方式
                cudWinSpeech:'',//获奖感言
                cudMemo:'',//备注
                cudWinDate:'',//中奖日期
                cudAwardDate:'',//发奖日期
                cudPayType:'',//收款方式
                cudBankCardNo:'',//银行卡号
                cudBonusProperty:[],//奖金性质
            },
            showCollapse:'1',
            showCollapse1:'1',
            loading:false,
            fileUploadUrl:process.env.UPDOWN_ROOT,
            fileList:[],
            fileListDownLoad:[],
            flowDetails:{
                nextActOptions:[],
                approvePerson:[],
                approvePersonId:[],//保存待处理人ID
                activityName:'010',
                isEnd:false,
            },
            flow_access:{
                next_deal_id:[],
                draftId:'',
                task_type:'',//任务类型
                mergeTask:'0',//合并任务
                soltCount:'1',//任务处理规则
                resign:'',//会签类型
                reselMan:'',//是否重选快速审批人
                act_name:'',//当前节点名称
                now_deal_act:'010',//当前节点
                deal_answer:'1',//同意 还是退回
                next_deal_act:'',//下一节点
                next_deal_name:[],//下一处理人 pxmwrya 
                next_deal_name_type:'',//处理人类型
                deal_suggest:'',//审批意见
                copygive:"",//抄送人
                approveMan:'',//当前提交人 自己
                procInstId:'',//流程实例ID
                sn:'',//sn
                backAct:'',//退回节点  020
                backMan:'',//退回人
                procSetId:'',//流程集ID 兑奖流程 463
                fullName:store.state.proc.procFullName,//流程全名
                procChName:'',//流程中文名
                procVerId:'',
            },
            fileProps:[ //文件上传的属性
                {prop:'fileRealName',label:'文件名'},
                {prop:'createTime',label:'上传时间'},
            ],

        }
    },
    methods: {
        goback(){
            this.$router.back();
        },
        delFiles(row){//删除上传文件
            let _this = this;
            delFile({fileId:row.fileId}).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    _this.fileListDownLoad.splice(_this.fileListDownLoad.findIndex(item => item.fileId===row.fileId),1);
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });
        },
        addProc(){//添加流程
            //下一步处理人 设置   
            if(document.getElementById("appMan")!= null){
                this.flow_access.next_deal_name = document.getElementById("appMan").value.split(',');  
            }
            //保存草稿ID
            this.flow_access.id = this.$route.query.obj.id;
            //判断获奖表
            this.$refs['win'].validate((valid)=>{
                if(valid){
                    if(this.checkValid()){
                        //设置关联文件
                        this.flow_access.fileList = this.fileListDownLoad;
                        this.win.cudBonusProperty = this.win.cudBonusProperty.join(',');
                        // this.flow_access.copygive = document.getElementById("sendToMan").value;
                        //处理抄送人
                        // let copygiveMans = document.getElementById("sendToMan").value;
                        // let copygiveIds = [];
                        // if(copygiveMans !=""){
                        //     let mans = copygiveMans.split(',');
                        //     for(let i = 0; i < mans.length; i++){
                        //         copygiveIds.push(mans[i].substr(1,mans[i].lastIndexOf(']')-1));
                        //     }
                        //     this.flow_access.copygive = copygiveIds.join(",");
                        // }

                        let _this = this;
                        this.flow_access.win = this.win;
                        //存储数据
                        commitWinAndDraft(this.flow_access).then((result) => {
                            if(result.status == "200" && result.data.code=="0"){
                                _this.$alert(_this.$t('dft.commitSuccess'),_this.$t('cm.tips'),{
                                    callback:_ => {
                                        _this.$router.push("/already_done_task");
                                    }
                                });
                            }else{
                                _this.$alert(result.data.msg,_this.$t('cm.tips'));
                            }
                        }).catch((err) => {
                            _this.$alert(err,_this.$t('cm.tips'));
                        });
                    }
        
                }else{
                    return false;
                }
            })  
        },
        editMyDraft:function(){//保存草稿
            //下一步处理人设置
            if(document.getElementById("appMan") != null && document.getElementById("appMan").value != ""){
                this.flow_access.next_deal_name = document.getElementById("appMan").value.split(',');  
            }
            //保存草稿ID
            this.flow_access.draftId = this.$route.query.obj.id;
            //判断业务表数据  判断获奖表
            this.flow_access.isSaveDraft = "1";//说明是保存草稿
            this.$refs['win'].validate((valid)=>{
                if(valid){
                    if(this.checkValid()){
                        //设置关联文件
                        this.flow_access.fileList = this.fileListDownLoad;
                        this.win.cudBonusProperty = this.win.cudBonusProperty.join(',');

                        let _this = this;
                        this.flow_access.win = this.win;

                        //调用保存草稿后台
                        editDraft(this.flow_access).then((result) => {
                            if(result.status == "200" && result.data.code == "0"){
                                _this.$router.push("/mydraft");
                            }else{
                                _this.$alert(result.data.msg,_this.$t('cm.tips'));
                            }
                        }).catch((err) => {
                            _this.$alert(err,_this.$t('cm.tips'));
                        });
                    }
                }
            });
        },
        checkValid(){//提交前的检验
            if(this.flow_access.deal_answer == ""){
                this.$alert("请选择处理结论!",this.$t('cm.tips'));
                return false;
            }else if(this.flow_access.next_deal_act == ""){
                this.$alert("请选择下一环节!",this.$t('cm.tips'));
                return false;
            }else if(this.flow_access.next_deal_name == "" && this.flow_access.backMan =="")
            {
                this.$alert("请选择下一步处理人",this.$t('cm.tips'));
                return false;
            }else{
                return true;
            }
        },
        upfileBack(response, file, fileList){//上传文件时的回调
            this.loading = false;
            if(response.code == "0"){
                this.fileListDownLoad.push(response.data);
            }else{
                this.$alert(response.msg,this.$t('cm.tips'));
            }      
        },
        beforeUpload(file){//上传文件之前的处理
            //在这里进行上传文件的设置
            let type = file.name.substring(file.name.lastIndexOf('.')+1);
            const limitSize = file.size / 1024 /1024 < 10; //文件大小限制
            if(!limitSize){
                this.$alert("上传文件大小不能超过10M",this.$t('cm.tips'));
            }
            return limitSize;
        },
        loadingFile(){
            this.loading = true;
        },
        uplofileError(){
            this.loading = false;
        },
        initData(){//初始化数据
            let obj = this.$route.query.obj;
            let formNo = obj.formno;//业务表单ID
            let id = obj.id;//草稿ID
            this.getProcInfo();
            this.getFormData(formNo);
            this.getFileList(formNo);
            this.getMyDraftDetails();
        },
        getFormData(formNo){//获取业务数据
            let _this = this;
            getWinDetailsById(formNo).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    _this.win = result.data.data;
                    if(result.data.data.cudBonusProperty != null){
                        _this.win.cudBonusProperty = result.data.data.cudBonusProperty.split(',');//处理奖金性质
                    }else{
                        _this.win.cudBonusProperty = [];
                    }
                    _this.win.memo = result.data.data.cudMemo;
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });
        },
        getFileList(formNo){//获取上传文件列表
            let _this = this;
            let params = {winId:formNo};
            findFileList(params).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    if(result.data.data != null){
                        _this.fileList = result.data.data;
                        _this.fileListDownLoad = result.data.data;
                    }
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });
        },
        getMyDraftDetails(){//获取流程草稿详细数据  在obj中
            let obj = this.$route.query.obj;
            this.flow_access.act_name = obj.activityname; //节点名称
            this.flow_access.next_deal_act = obj.targetactmetadata; //下一处理环节
            this.flow_access.procSetId = obj.procsetid; //流程集ID
            this.flow_access.procChName = obj.processname; //流程名称
            //待处理人
            let userIds = obj.account.split(",");
            let userNames = obj.userchsname.split(",");
            for(let i = 0; i < userIds.length; i++){
                this.flow_access.next_deal_name.push("["+ userIds +"]"+ userNames);
            }
            this.flow_access.next_deal_id.push(...userIds);
        },
        /**
         * 获取流程相关信息
         */
        getProcInfo(){
            this.getSomeInfo(this.$store.state.proc.procId);
        },
        getSomeInfo(procVerId){
            //获取流程的开始节点、下一节点还有下一节点处理人
            let _this = this;
            getStartAct(procVerId).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    let data = result.data.data.data;
                    //获取下一处理环节 
                    _this.getNextDealNode(data);
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });
        },
        getNextDealNode:function(data){//获取下一节点 通过 下一步点处理人接口
            let _this = this;
            let params = {
                actId: data.act_id,
                procInstId: 0,
                procId: data.proc_id,
                node: data.act_metadata,
            }
            getNextApprovePerson(params).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    let data = result.data.data.data;
                    this.getNextNodeInfo(data);
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });
        },
        //获取下一节点详情
        getNextNodeInfo:function(data){
            //获取流程配置中的流程节点信息  可以存储在store中
            let _this = this;
            let params = {
                fullName: this.$store.state.proc.procFullName,
                procSetId: this.$store.state.proc.procSetId
            };
            getWFConfigActivity(params).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    //存在多个下一环节的情况
                    for(const metadata in data){
                        let d = result.data.data.data;
                        for(let i = 0; i < d.length; i++){
                            if(d[i].actMetaData == metadata){
                                _this.unifyUser(data[metadata]);//处理下一步处理人
                                _this.getNextNodeDetails(d[i]);
                            }        
                        }
                    }
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });
        },
        //获取下一节点详细信息
        getNextNodeDetails(arr){
            let _this = this;
            getBpmPscActInfo({actId:arr.actID}).then((result) => {
                if(result.status == "200" && result.data.code == "0"){
                    let data = result.data.data.data;
                    //获取下一步点处理人
                    _this.flowDetails.nextActOptions.push(data);
                }else{
                    _this.$alert(result.data.msg,_this.$t('cm.tips'));
                }
            }).catch((err) => {
                _this.$alert(err,_this.$t('cm.tips'));
            });

        },
        //统一用户格式
        unifyUser:function(users){
            for(let i = 0; i < users.length; i++){
                if(typeof(users[i].item_principal_desc) != "undefined" && typeof(users[i].item_principal_desc) != null){
                    this.flowDetails.approvePerson.push("["+users[i].item_principal+"]"+users[i].item_principal_desc);
                    this.flowDetails.approvePersonId.push(users[i].item_principal);
                }
            }
        },
    },
    created() {
        //填充业务数据和流程数据
        this.initData();
    },
    mounted() {
        
    },
    computed: {
        winRules:function(){
            return {
                cudWinLevel:[
                    {required:true,message:this.$t('fe.input_winLevel'),trigger:'change'}
                ],
                cudPrizeAmount:[
                    {required:true,message:this.$t('fe.input_prizeAmount'),trigger:'blur'}
                ],
                cudWinName:[
                    {required:true,message:this.$t('fe.input_winName'),trigger:'blur'}
                ],
                cudPhone:[
                    {required:true,message:this.$t('fe.input_phone'),trigger:'blur'}
                ],
                cudPayType:[
                    {required:true,message:this.$t('fe.input_cudPayType'),trigger:'change'}
                ],
                cudAwardDate:[
                    {required:true,message:this.$t('fe.input_cudAwardDate'),trigger:'change'}
                ],
                cudWinDate:[
                    {required:true,message:this.$t('fe.input_cudWinDate'),trigger:'change'}
                ]
            }
        }
    },
}